package com.fenghuajueli.lib_net.common;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.fenghuajueli.lib_net.BuildHeadersListener;
import com.fenghuajueli.lib_net.LoggingInterceptor;
import com.fenghuajueli.lib_net.converter.GsonConverterFactory;
import com.fenghuajueli.lib_net.converter.StringConverterFactory;
import com.fenghuajueli.lib_net.observer.RxAndroidCallAdapterFactory;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;

public class RetrofitUtils {

    private static OkHttpClient okHttpClient = null;


    public static Retrofit.Builder getRetrofitBuilder(String baseUrl) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
        return new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addConverterFactory(StringConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addCallAdapterFactory(RxAndroidCallAdapterFactory.create())
                .baseUrl(baseUrl);
    }

    public static Retrofit.Builder getRetrofitStringBuilder(String baseUrl) {
        return new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(StringConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addCallAdapterFactory(RxAndroidCallAdapterFactory.create())
                .baseUrl(baseUrl);
    }

    public static void init(Context context, BuildHeadersListener buildHeadersListener) {
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new LoggingInterceptor());
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder=new OkHttpClient.Builder();
        okHttpClient =builder
                .readTimeout(15000, TimeUnit.MILLISECONDS)
                .connectTimeout(15000, TimeUnit.MILLISECONDS)
                .addInterceptor(new HttpHeaderInterceptor() {

                    @Override
                    public Map<String, String> buildHeaders() {
                        return buildHeadersListener.buildHeaders();
                    }
                })
                .addInterceptor(logInterceptor)
                .build();
    }




    public static OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }
}
